package servlet;

import entity.User;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Author:shixiaojun@itany.com
 * Date:2022/4/22 15:20
 * Version:1.0-SNAPSHOT
 * Description:
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        if("/findAll.user".equals(path)){
            findAll(request,response);
        }
        if("/findById.user".equals(path)){
            findById(request,response);
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String id = request.getParameter("id");
        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            rs = ps.executeQuery();
            if(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                // out.print("{'id':"+user.getId()+",'username':'"+user.getUsername()+"','password':'"+user.getPassword()+"','phone':'"+user.getPhone()+"','address':'"+user.getAddress()+"'}");
                // 由apache提供的JSON工具
                // 该工具提供了将一个Java对象转换成JSON对象的方法
                // 且提供了将一个JSON对象转换成JSON格式的字符串的方法
                // 1.JSONObject jsonObject = JSONObject.fromObject(Object obj)
                // 将一个Java对象转换成JSON对象
                // JSONObject类型:JSON对象类型
                JSONObject jsonObject = JSONObject.fromObject(user);
                // JSONObject中提供了toString方法
                // 表示将一个JSON对象转换成JSON格式的字符串
                String userJson = jsonObject.toString();
                System.out.println(userJson);
                out.print(userJson);
                // 在JSON工具中还提供了将对象集合转换成JSON数组的方式
                // JSONArray array = JSONArray.fromObject(Object obj)
                // 此时的参数是一个集合或者数组
                // 返回值表示的是JSON数组
                // JSONArray也提供toString方法
                // 将一个JSON数组转换成JSON格式的字符串
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 使用JDBC访问数据的方式将对应的员工信息插入到数据库中
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        String url = "jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8";
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,"root","");
            String sql = new StringBuffer()
                    .append(" select id,username,password,phone,address ")
                    .append(" from t_user")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while(rs.next()){
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                users.add(user);
            }
            request.setAttribute("users",users);
//            request.getRequestDispatcher("/list.jsp").forward(request,response);
            request.getRequestDispatcher("/jquery/list.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
